iT邦幫忙

2021 iThome 鐵人賽

DAY 16
0
自我挑戰組

Android kotlin &MVVM系列 第 16

Android學習筆記16

  • 分享至 

  • xImage
  •  

因為如果把dialog寫在viewmodel裡面,之後在自動化測試的時候可能會出問題,所以在mvvm架構底下,我們另外寫了一個dialogviewmodel,對應到dialog的view
首先先建立一個dialogviewmodel
class DialogViewModel: ViewModel() {
val result: MutableLiveData = MutableLiveData()
}
然後建立一個狀態資訊
//表達一個元件的狀態
//sealed可以使用dataclass傳值
sealed class MainDialogResult {
data class Ok(val message: String): MainDialogResult()
object Cancel: MainDialogResult()
//也可以使用object變成跟enum一樣的用法
}
然後在dialogfragment中這樣調用

class FragmentDialog: DialogFragment() {
    private val viewModel: DialogViewModel<MainDialogResult> by activityViewModels()
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val view: View = inflater.inflate(R.layout.dialogfragment , container , false)
        val accountEditView = view.findViewById<EditText>(R.id.account)
        val passwordEditView = view.findViewById<EditText>(R.id.password)
        val loginButton = view.findViewById<Button>(R.id.login)
        val cancelButton = view.findViewById<Button>(R.id.cancel)
        val progressBar = view.findViewById<ProgressBar>(R.id.progressBar)
        val pgBar = view.findViewById<ProgressBar>(R.id.progressBar2)
        progressBar.visibility = View.VISIBLE
        pgBar.max = 100
        Thread{
            for (i in 0..100){
                pgBar.progress = i
                //Thread.sleep(500)
                SystemClock.sleep(500)
            }
        }.start()
        pgBar.progress = 0

        val message = "ok"
        loginButton.setOnClickListener {
            viewModel.result.postValue(MainDialogResult.Ok(message))
            dismiss()
        }

        cancelButton.setOnClickListener {
            viewModel.result.postValue(MainDialogResult.Cancel)
            dismiss()
        }

        return view
    }
}

最後在activity中這要調用即可

val fm = supportFragmentManager
val dialog = FragmentDialog()
dialog.show(fm,"Blossom")

viewModel.result.observe(this){
    when(it){
        is MainDialogResult.Ok ->{
            Toast.makeText(this,it.message,Toast.LENGTH_SHORT).show()
        }
        is MainDialogResult.Cancel ->{
            Toast.makeText(this,"cancel",Toast.LENGTH_SHORT).show()
        }
    }

https://ithelp.ithome.com.tw/upload/images/20210925/20141791f44aeL7fcK.png


上一篇
Android學習筆記15
下一篇
Android學習筆記17
系列文
Android kotlin &MVVM30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言